<?php
/**
 * Created by PhpStorm.
 * User: netstan
 * Date: 14-8-23
 * Time: 上午12:39
 */

function base_Hash($key){

    $str = substr(md5($key),0,8);
    $prime = 31;
    $hash = 5381;

    for($i = 0; $i < 8; $i++ ) {
        $hash = $hash * $prime + ord($str{$i});
        ++$i;
    }

    return $hash & 0x7fffffff;
}

class FlexiHash{

    //服务器列表
    private $server_List = array();
    // 是否已经排过序
    private $is_Sorted = FALSE;

    function addServer($server){
        $hash =  base_Hash($server);

        if(!isset($this->server_List[$hash])){
            $this->server_List[$hash] = $server;
        }

        $this->is_Sorted = FALSE;
        return TRUE;
    }

    function removeServer($server){
        $hash = base_Hash($server);

        if(isset($this->server_List[$hash])){
            unset($this->server_List[$hash]);
        }

        $this->is_Sorted = FALSE;
        return TRUE;
    }

    function lookup($key){
        $hash = base_Hash($key);

        if(!$this->is_Sorted){
           krsort($this->server_List,SORT_NUMERIC);
           $this->is_Sorted = true;
        }

        var_dump($key.'--'.$hash);
        var_dump($this->server_List);
        foreach($this->server_List as $pos => $server){
            if($hash >= $pos) return $server;
        }

        return $this->server_List[count($this->server_List)-1];
    }


}

//添加服务器

$server = new FlexiHash();
$server->addServer('192.168.1.10');
$server->addServer('192.168.1.11');
$server->addServer('192.168.1.12');
$server->addServer('192.168.1.13');

$ip = array();
$key1 = 'nginx';
$key2 = 'mysql';
$key3 = 'php';
$ip[$key1] = $server->lookup($key1);
$ip[$key2] = $server->lookup($key2);
$ip[$key3] = $server->lookup($key3);

var_dump($ip);

$server->removeServer('192.168.1.12');
$server->removeServer('192.168.1.13');
$server->addServer('192.168.1.9');
$server->addServer('192.168.1.14');
$ip[$key1] = $server->lookup($key1);
$ip[$key2] = $server->lookup($key2);
$ip[$key3] = $server->lookup($key3);
var_dump($ip);